package com.lagou.container;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StandardContext{
    private String name;
    private String baseUrl;
    private Map<String, StandardWrapper> wrapperMap = new HashMap<String, StandardWrapper>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBaseUrl() {
        return baseUrl;
    }

    public void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public Map<String, StandardWrapper> getWrapperMap() {
        return wrapperMap;
    }

    public void setWrapperMap(Map<String, StandardWrapper> wrapperMap) {
        this.wrapperMap = wrapperMap;
    }

    public StandardContext(String name, String baseUrl) {
        this.name = name;
        this.baseUrl = baseUrl;
    }

    public StandardContext() {
    }

    public void init() {
        //1、根据应用包找到配置文件，读取配置文件 E:/workspace/lagou/tomcat/miniCat4.0/src/webapp/demo1
        String webUrl = baseUrl + "/" + "web.xml";
        File webXml = new File(webUrl);
        SAXReader saxReader = new SAXReader();

        if(webXml != null){
            try {
                Document document = saxReader.read(webXml);
                Element rootElement = document.getRootElement();
                List<Element> servletList = rootElement.selectNodes("//servlet");
                servletList.forEach(servlet ->{
                    //获取servletName
                    String servletName = servlet.selectSingleNode("servlet-name").getStringValue();
                    //获取servletClass
                    String servletClass = servlet.selectSingleNode("servlet-class").getStringValue();

                    Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                    String servlteUrl = servletMapping.selectSingleNode("url-pattern").getStringValue();

                    try {
                        StandardWrapper standardWrapper = new StandardWrapper(servletName, servletClass);
                        //把servlet对象和
                        wrapperMap.put(servlteUrl, standardWrapper);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });

            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }
    }
}
